import requests
import os
import re


# headers = {
#     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
# }
# url = 'https://m804.music.126.net/20241125202001/60ffb1df182b78bd58f428d5dda41130/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/28481684242/6840/5be9/6ebb/56ebe9913ba91b0d160fd55feeacc354.m4a?authSecret=00000193632cd15914260a3b18b01527'
# response = requests.get(url=url, headers=headers)
# music_content = response.content
#
# if not os.path.exists('data'):
#     os.mkdir('data')
# with open('data/于是.mp4', 'wb') as f:
#     f.write(music_content)

def get_request(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
    }
    response = requests.get(url=url, headers=headers)
    return response


def save(fie_name, content):
    if not os.path.exists('music'):
        os.mkdir('music')
    with open('music/' + fie_name + '.mp3', 'wb') as f:
        f.write(content)


def main():
    link = 'https://music.163.com/discover/toplist?id=3778678'
    html = get_request(link).text
    info = re.findall(r'<a href="/song\?id=(\d+)">(.*?)</a>', html)
    for music_id, title in info:
        music_url = f'https://music.163.com/song/media/outer/url?id={music_id}'
        print(music_url)
        res = get_request(music_url)
        save(title, res.content)


if __name__ == '__main__':
    main()
